package com.efounder.builder.base.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
/**
 * <p>
 * Title:
 * </p>
 * 
 * <p>
 * Description:
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * 
 * <p>
 * Company:
 * </p>
 * 
 * @author Skyline
 * @version 1.0
 */
public class JSONUtil {
	/**
	 *
	 */
	protected JSONUtil() {
	}

	/**
	 * 
	 * @param obj
	 *            Object
	 * @return String
	 * @throws Exception
	 */
	public static String obj2json(Object obj) throws Exception {
		return null;
	}

	private static JsonConfig jsonConfig = null;

	public static synchronized JsonConfig getJsonConfig() {
		if (jsonConfig == null) {
			jsonConfig = new JsonConfig();
			//设置循环引用的项
//			jsonConfig.setExcludes(new String[]{"_Self_RowSet","master","parentRowSet","childRowSet"});
	        jsonConfig.setIgnoreDefaultExcludes(false); 
	        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
		}
		jsonConfig.registerDefaultValueProcessor(Integer.class,
				new DefaultValueProcessor() {
			public Object getDefaultValue(Class type) {
				return null;
			}
		});
		jsonConfig.registerDefaultValueProcessor(Double.class,
				new DefaultValueProcessor() {
			public Object getDefaultValue(Class type) {
				return null;
			}
		});
		jsonConfig.registerDefaultValueProcessor(Long.class,
				new DefaultValueProcessor() {
			public Object getDefaultValue(Class type) {
				return null;
			}
		});
		return jsonConfig;
	}

	public static Object JSON2Bean(String jsonStr, Class clazz) {
		String simpleName = clazz.getSimpleName();
		JSONObject jsonObject = JSONObject.fromObject(jsonStr, getJsonConfig());
		Object object = JSONObject.toBean(jsonObject, clazz);
		return object;
	}

	//将object转成json
	public static String bean2JSON(Object object) {
		return JSONSerializer.toJSON(object, getJsonConfig()).toString();
	}

	/**
	 * 将json转成object
	 * @param json
	 * @return
	 */
	public static JSONObject JSON2Object(String json) {
		return JSONObject.fromObject(json, getJsonConfig());
	}
	
	/**
	 * 将json转成Array
	 * @param json
	 * @return
	 */
	public static JSONArray JSON2Array(String json) {
		return JSONArray.fromObject(json, getJsonConfig());
	}

	/**
	 * 将json转成Map
	 * @param jsonString
	 * @return
	 */
	public static Map getMapFromJson(String jsonString) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, jsonObject.get(key));
		}
		return map;
	}
	
	//将EFDataSet转成json
	public static String DataSet2JSON(EFDataSet dataset) {
		return DataSet2JSON(dataset,false);
	}
	
	public static String DataSet2JSON(EFDataSet dataset,boolean isRecursion) {
		List jsonList = new ArrayList();
		String str;
		if(isRecursion){
			jsonList = DataSet2JSONList(dataset,isRecursion);
		}else{
			List<EFRowSet> rowSetList = dataset.getRowSetArray();
			if( null == rowSetList)
				return "";
			for( EFRowSet rowSet : rowSetList ){			
				jsonList.add(rowSet.getDataMap());
			}
		}
		str =  JSONUtil.bean2JSON(jsonList);
		return str;
	}
	
	
	public static List DataSet2JSONList(EFDataSet dataset,boolean isRecursion) {
		List jsonList = new ArrayList();
		List<EFRowSet> rowSetList = dataset.getRowSetArray();
		if( null == rowSetList)
			return null;
		Map rowMap = null;
		for( EFRowSet rowSet : rowSetList ){			
			//str= JSONUtil.bean2JSON(rowSet.getDataMap());
			rowSet.getDataMap().remove("_Self_RowSet");
			String dsTypes[] = rowSet.getDSTypes();
			isRecursion = !(dsTypes == null || dsTypes.length == 0);
			if(isRecursion){
					rowMap = RowSet2JSONMap(rowSet,isRecursion);
					if(rowMap != null)
						jsonList.add(rowMap);
			}else{
				jsonList.add(rowSet.getDataMap());
			}
		}
		return jsonList;
	}
	
	//将EFRowSet转成json
	public static String RowSet2JSON(EFRowSet rowset) {
		return RowSet2JSON(rowset, false);
	}
	
	public static String RowSet2JSON(EFRowSet rowset,boolean isRecursion) {
		return JSONUtil.bean2JSON(RowSet2JSONMap(rowset, isRecursion));
	}
	
	public static Map RowSet2JSONMap(EFRowSet rowset,boolean isRecursion) {
		Map datasetMap = new HashMap();
		rowset.getDataMap().remove("_Self_RowSet");
		datasetMap.put("_Self_RowSet", rowset.getDataMap());
		String dsTypes[] = rowset.getDSTypes();

		if(dsTypes == null || dsTypes.length==0) return rowset.getDataMap();
		for(int i =0;i<dsTypes.length;i++){

			List rowSetList = JSONUtil.DataSet2JSONList(rowset.getDataSet(dsTypes[i]),isRecursion);

			if(rowSetList != null){
				datasetMap.put(dsTypes[i], rowSetList);
			}
		}

		return datasetMap;
	}
	
	public static EFRowSet JSON2RowSet(String jsonStr){
		EFRowSet rowSet = EFRowSet.getInstance();
		JSONObject jsonObject = JSONUtil.JSON2Object(jsonStr);
		if(jsonObject.get("_Self_RowSet")==null){
			for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
				String key = (String) iter.next();
				rowSet.put(key, jsonObject.get(key));
			}
		}else{
			rowSet = JSON2RowSet(jsonObject.getString("_Self_RowSet"));
			jsonObject.remove("_Self_RowSet");
			for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
				String key = (String) iter.next();
				EFDataSet dataSet = EFDataSet.getInstance(key);
				rowSet.setDataSet(key, dataSet);
				
				JSONArray jsonArray = jsonObject.getJSONArray(key);
				for(int i=0;i<jsonArray.size();i++){				
					dataSet.addRowSet(JSON2RowSet(jsonArray.get(i).toString()));
				}
			}
		}
		return rowSet;
	}
	
	public static EFDataSet JSON2DataSet(String jsonStr){
		EFDataSet dataSet = EFDataSet.getInstance("json");

		JSONArray jsonArray = JSONUtil.JSON2Array(jsonStr);

		for(int i=0;i<jsonArray.size();i++){				
			dataSet.addRowSet(JSON2RowSet(jsonArray.get(i).toString()));
		}

		return dataSet;
	}
	
	//将Map转成json
	public static String Map2JSON(Map mapObject) {
		//获取map集合中的所有键的Set集合  
        Set<String> keySet = mapObject.keySet();  
        //有了Set集合就可以获取其迭代器，取值  
        Iterator<String> it = keySet.iterator();  
        while (it.hasNext())  
        {  
            String key = it.next();  
            Object oo = mapObject.get(key); 
            if(oo instanceof EFRowSet){
				Map mo =  JSONUtil.RowSet2JSONMap((EFRowSet)oo,true);
				mapObject.put(key, mo);
			}else if(oo instanceof EFDataSet){
				List l = JSONUtil.DataSet2JSONList((EFDataSet)oo,true);
				mapObject.put(key, l);
			}

        } 


		String str =  JSONUtil.bean2JSON(mapObject);
		return str;
	}
}
